//
//  CXLRefreshControl.swift
//  weibo1990
//
//  Created by 曹晓龙 on 15/10/22.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit

/// 箭头选中临界点
private let CXLRefreshControlFlag: CGFloat = -60

/// 下拉刷新视图
class CXLRefreshControl: UIRefreshControl {

    override func beginRefreshing() {
        super.beginRefreshing()
        
        refreshView.startAnim()
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopAnim()
    }
    
    //MARK:- 构造方法
    override init() {
        
        super.init(frame: CGRectZero)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)
    }
    
    /// 设置UI界面
    private func setupUI(){
        
        tintColor = UIColor.clearColor()
        
        addSubview(refreshView)
        
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            make.size.equalTo(refreshView.bounds.size)
        }
        
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    
    deinit{
        
        removeObserver(self, forKeyPath: "frame")
    }
    
    /// KVO监听
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
            
            return
        }
        
        if refreshing {
            return
        }
        
        if frame.origin.y < CXLRefreshControlFlag && !refreshView.rotationFlag{
            
            refreshView.rotationFlag = true
            
        } else if frame.origin.y > CXLRefreshControlFlag && refreshView.rotationFlag{
            
            refreshView.rotationFlag = false
        }
        
    }
    
    /// 刷新视图
    private lazy var refreshView:CXLRefreshView = CXLRefreshView.refreshView()
}

/// 自定义下拉刷新内部视图
class CXLRefreshView:UIView {
    
    private var rotationFlag = false {
        didSet{
            
            rotationTipIcon(rotationFlag)
        }
    }
    
    ///  转轮
    @IBOutlet weak var rotationIcon: UIImageView!
    
    ///  箭头
    @IBOutlet weak var tipIcon: UIImageView!
    
    ///  提示视图
    @IBOutlet weak var tipView: UIView!
    
    ///  旋转转轮动画
    private func startAnim(){
    
        tipView.hidden = true

        let key = "transform.rotation"
        
        if rotationIcon.layer.animationForKey(key) != nil {
            return
        }
        let anim = CABasicAnimation(keyPath: key)
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.removedOnCompletion = false
        
        rotationIcon.layer.addAnimation(anim, forKey: key)
    }
    ///  停止转轮动画
    private func stopAnim(){
        tipView.hidden = false
        rotationIcon.layer.removeAllAnimations()
    }
    
    ///  选中箭头
    private func rotationTipIcon(rotationFlag:Bool){
        
        var angle = CGFloat(M_PI)
        
        angle += rotationFlag ? -0.0001 : +0.001
        
        UIView.animateWithDuration(0.5) { () -> Void in
            
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
    }
    
    
    ///  类方法,创建视图
    private class func refreshView() ->CXLRefreshView{
        
        let nib = UINib(nibName: "CXLRefreshView", bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil).last as! CXLRefreshView
    }
    

    
}